package com.qf.shiroboot.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class UserController {

    @GetMapping("/login")
    public String login(){
        return "login";
    }

    @PostMapping("/doLogin")
    public String login(String username, String password, Model model){
        //1. 获取subject
        Subject subject = SecurityUtils.getSubject();

        //2. 通过subject执行认证操作
        try {
            subject.login(new UsernamePasswordToken(username,password));

            // 登录成功
            return "redirect:/index";
        } catch (AuthenticationException e) {
            e.printStackTrace();
            // 用户名或密码错误
            model.addAttribute("info","用户名或密码错误!");
            return "login";
        }
    }

}
